define(function(require, exports){
	var $ = require("jquery");
	var pubjs = require('pubjs');
	var view = require('@base/view');
	var util = require('util');
	var dspUtil = require('dspUtil');
	var popwin = require('@base/dialog').base;

	var Base = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				tplFile: '/tpl/materialGroup/modules/edit.tpl',
				urlCheckWhisky: 'whisky/batchCheck',
				hideMethod: false, // 隐藏可操作按钮
				canImport: false, // 显示导入按钮
				canSave: false, // 显示保存按钮
				vModel: {
					canImport: false
					,canSave: false
					,data: []
					,head: [LANG('创意包'), LANG('落地页')]
					,emptyText: LANG('请添加创意包或导入素材组')
					,hideMethod: false
				},
				vMethods: {
					vmPreview: this.vmPreview
					,vmAddSweety: this.vmAddSweety
					,vmAddWhisky: this.vmAddWhisky
					,vmRemove: this.vmRemove
				}
			});

			this.$sweetyParam = {};
			this.$whiskyParam = {};
			this.$indexSweety = -1;
			this.$indexWhisky = -1;
			this.$sweetyIds = [];
			this.$whiskyIds = [];
			this.$data = [];
			this.Super('init', arguments);
		}
		,afterBuild:function(){
			this.createDelay('sweetyPop','modules/selectModule.sweety', {
				silence: false
			});
			this.createDelay('whiskyPop','modules/selectModule.whisky', {
				silence: false
			});
			this.createDelay('materialPop','modules/selectModule.materialGroup', {
				silence: false
			});
			this.createDelay('namePop','materialGroup/popwin/edit.name', {
			});

			var self = this;
			this.createDelay(true, function () {
				self.buildFromTemplate({
					grid: {
						'class': 'ss'
					},
					add: {
						value: LANG('添加')
						,'class': 'btn btn-primary mr10'
						,width: null
					},
					addLine: {
						value: LANG('分行添加')
						,'class': 'btn btn-primary mr10'
						,width: null
					},
					ref: {
						value: LANG('引用素材组')
						,'class': 'btn btn-primary mr10'
						,width: null
					},
					copy: {
						value: LANG('复制素材组')
						,'class': 'btn btn-primary mr10'
						,width: null
					},
					save: {
						value: LANG('保存为素材组')
						,'class': 'btn btn-confirm'
						,width: null
					}
				});
			});
		}
		,afterBuildTemplate: function () {
			this.reset();
		}
		,onInputClick: function(ev) {
			if(ev.from._.pid === this._.guid)
			{
				var c = this.getConfig();
				switch (ev.name) {
					case 'add':
						this.$addLine = false;
						this.$indexSweety = -1;
						this.showSweety();
						break;
					case 'addLine':
						this.$addLine = true;
						this.$indexSweety = -1;
						this.showSweety();
						break;
					case 'copy':
						this.$isCopy = true;
						this.showMaterialGroup();
						break;
					case 'ref':
						this.$isCopy = false;
						this.showMaterialGroup();
						break;
					case 'save':
						this.save();
						break;
					default :
						return false;
				}

				return false;
			}
		}
		,checkEmpty: function () {
			var self = this;
			var data = self.vm.$.data;
			self.$sweetyIds = [];
			self.$whiskyIds = [];
			util.each(data, function (item) {
				util.each(item.Sweety, function (v) {
					if(v && v._id)
					{
						self.$sweetyIds.push(v._id);
					}
				});

				util.each(item.Whisky, function (v) {
					if(v && v._id)
					{
						self.$whiskyIds.push(v._id);
					}
				});

				if(item.Sweety.length === 0 && item.Whisky.length === 0)
				{
					return null;
				}
			});
		}
		,vmRemove: function (parent, index, type) {
			var data = this.vm.$.data;
			if(type === 1)
			{
				data[parent].Sweety.splice(index, 1);
			}
			else if(type === 2)
			{
				data[parent].Whisky.splice(index, 1);
			}
			else if(type === 3)
			{
				for(var i = parent+1; i < data.length; i++)
				{
					if(data[i].IsFirst || !data[i].IsTemplate)
					{
						break;
					}
				}

				data.splice(parent, i - parent);
			}

			this.checkEmpty();
		}
		,vmPreview: function (Cover) {
			window.open(Cover && Cover.previewUrl || Cover);
		}
		,vmAddWhisky: function (index) {
			this.$indexWhisky = index;
			this.showWhisky();
		}
		,vmAddSweety: function (index) {
			this.$indexSweety = index;
			this.showSweety();
		}
		,showMaterialGroup: function () {
			this.$.materialPop.reset().load().show();
		}
		,showWhisky: function () {
			var data = this.vm.getCopy('data');
			var t = data[this.$indexWhisky].Whisky || [];
			var value = [];
			util.each(t, function (item) {
				if(item._id)
				{
					value.push(item);
				}
			});

			this.$.whiskyPop.reset().setParam(this.$whiskyParam).load().setValue(value).show();
		}
		,showSweety: function () {
			var param = util.clone(this.$sweetyParam);
			var value = [];
			var data = this.vm.getCopy('data');
			if(this.$indexSweety !== -1)
			{
				value = data[this.$indexSweety].Sweety || [];
				var ids = [];
				util.each(value, function (item) {
					ids.push(item._id);
				});

				param.excludeIds = dspUtil.difference(this.$sweetyIds, ids).toString();
			}
			else
			{
				param.excludeIds = this.$sweetyIds.length ? this.$sweetyIds.toString() : null;
			}

			this.$.sweetyPop.reset().setParam(param).load().setValue(value).show();
		}
		// 添加创意包消息
		,onSelectSweety: function(ev) {
			var i, item;
			if(this.$indexSweety !== -1)
			{
				var sweety = this.$data[this.$indexSweety].Sweety = [];
				for(i = 0; i < ev.param.length; i ++)
				{
					item = ev.param[i];
					item.smallThumb = (item.Cover && item.Cover.thumb) + '&w=200&h=200';
					sweety.push(item);
				}
			}
			else
			{
				var t;
				if(!this.$addLine)
				{
					t = {
						Sweety: [],
						Whisky: []
					};

					this.$data.push(t);
				}

				for(i = 0; i < ev.param.length; i ++)
				{
					item = ev.param[i];
					this.$sweetyIds.push(item._id);
					item.smallThumb = (item.Cover && item.Cover.thumb) + '&w=200&h=200';

					if(this.$addLine)
					{
						t = {
							Sweety: [item],
							Whisky: []
						};

						this.$data.push(t);
					}
					else
					{
						t.Sweety.push(item);
					}

					if(item.Whisky)
					{

						if(item.Whisky._id)
						{
							item.Whisky.smallThumb = item.Whisky.Cover + '&w=200&h=200';
							item.Whisky.link = item.Whisky.Material;
							item.Whisky.name = item.Whisky.Name;
							t.Whisky.push(item.Whisky);
						}
						else
						{
							t.Whisky.push({
								isLink: true,
								link: item.WhiskyUrl,
								smallThumb: item.Whisky.thumb + '&w=200&h=200',
								name: '',
							});
						}
					}
				}
			}

			this.vm.$.data = this.$data;
			this.checkEmpty();
			return false;
		}
		// 添加落地页消息
		,onSelectWhisky: function(ev) {
			var old = this.$data[this.$indexWhisky].Whisky || [];
			var whisky = [];
			util.each(old, function (item) {
				if(item && !item._id)
				{
					whisky.push(item);
				}
			});

			for(var i = 0; i < ev.param.length; i ++)
			{
				var item = ev.param[i];
				item.smallThumb = item.Cover + '&w=200&h=200';
				item.link = item.Material;
				item.name = item.Name;
				whisky.push(item);
			}

			this.$data[this.$indexWhisky].Whisky = whisky;
			this.vm.$.data = this.$data;
			this.checkEmpty();
			return false;
		}
		,onSelectMaterialGroup: function (ev) {
			var self = this;
			var error = [];
			for(var i = 0; i < ev.param.length; i ++)
			{
				var item = ev.param[i];
				var state = true;
				util.each(item.Strategy, function (strategy) {
					var cm = dspUtil.intersection(self.$sweetyIds, strategy.SweetyIds);
					if(cm && cm.length)
					{
						error.push(item.Name);
						state = false;
						return false;
					}
				});

				if(state)
				{
					util.each(item.StrategyInfo, function (strategy, index) {
						var t = {
							Sweety: [], Whisky: []
						};

						if(!self.$isCopy)
						{
							t.IsTemplate = true;
							if(index === 0)
							{
								t._id = item._id;
								t.IsFirst = true;
								t.Name = item.Name;
							}
						}

						self.$data.push(t);
						var i = self.$data.length -1;
						self.$indexSweety = i;
						self.$indexWhisky = i;
						self.onSelectSweety({
							param: strategy.Sweety
						});

						self.onSelectWhisky({
							param: strategy.Whisky
						});
					});
				}
			}

			if(error && error.length)
			{
				pubjs.alert(LANG('以下素材组导入失败，存在重复的创意包 \r\n %1', error.join('\r\n')));
			}

			self.checkEmpty();
			return false;
		}
		,validate: function (data) {
			if(!data || !data.length)
			{
				pubjs.alert('请先选择相应的创意包落地页');
				return false;
			}

			for(var i = 0; i < data.length; i++)
			{
				if(!data[i].hasOwnProperty('RefId'))
				{
					if(!data[i].SweetyIds.length || !data[i].WhiskyIds.length)
					{
						pubjs.alert('创意包或落地页不能为空，请选择或删除');
						return false;
					}
				}
			}

			return true;
		}
		,validateInfo: function (data) {
			if(!data || !data.length)
			{
				pubjs.alert('请先选择相应的创意包落地页');
				return false;
			}

			for(var i = 0; i < data.length; i++)
			{
				if(!data[i].hasOwnProperty('RefId'))
				{
					if(!data[i].Sweety.length || !data[i].Whisky.length)
					{
						pubjs.alert('创意包或落地页不能为空，请选择或删除');
						return false;
					}
				}
			}
			return true;
		}
		,getWhiskyUrl: function (strategy) {
			var whiskyUrl = [];
			util.each(strategy, function (item) {
				util.each(item.WhiskyIds, function (id) {
					if(!util.isNumber(id))
					{
						whiskyUrl.push(id);
					}
				})
			});

			return whiskyUrl;
		}
		// 检查落地页是否有没保存成记录的并且是已经删除的，
		,checkWhiskyUrl: function (strategy, cb, getWhiskyUrl) {
			var self = this;
			if(!getWhiskyUrl)
			{
				getWhiskyUrl = this.getWhiskyUrl;
			}

			var whiskyUrl = getWhiskyUrl(strategy);
			if(whiskyUrl.length)
			{
				pubjs.loading.show();
				pubjs.mc.send(self.getConfig('urlCheckWhisky'), {Material: whiskyUrl}, function (err, result) {
					pubjs.loading.hide();
					if(err)
					{
						return pubjs.alert(err.message);
					}

					if(result && result.length)
					{
						var deleted = [];
						util.each(result, function (item) {
							if(item && item.IsDeleted)
							{
								deleted.push(item.whisky.OuterLink);
							}
						});

						if(deleted.length)
						{
							pubjs.confirm
							(
								LANG('已存在归档中的相同落地页，可能和其它投放中的推广组有关联关系，是否还原此落地页。\r\n %1', deleted.join('\n')),
								function(isOk)
								{
									if (isOk)
									{
										// 强制保存更新
										cb(true);
									}
								});
						}
					}
					else
					{
						cb();
					}
				});
			}
			else
			{
				cb();
			}
		}
		,getData: function(data){
			var self = this;
			data = data || this.vm.getCopy('data');
			var ret = [];
			util.each(data, function (item) {
				if(item.IsTemplate)
				{
					if(item.IsFirst)
					{
						ret.push({
							RefId: item._id
						});
					}
				}
				else
				{
					var t = {
						SweetyIds: [],
						WhiskyIds: []
					};
					util.each(item.Sweety, function (sweety) {
						t.SweetyIds.push(sweety._id);
					});

					util.each(item.Whisky, function (whisky) {
						t.WhiskyIds.push(whisky.isLink ? whisky.link : whisky._id);
					});

					ret.push(t)
				}
			});

			return ret;
		}
		,getInfo: function()
		{
			var data = this.vm.getCopy('data');
			return data;
/*			var ret = [];
			util.each(data, function (item) {
				if(item.IsTemplate)
				{
					if(item.IsFirst)
					{
						item.RefId = item._id;
						ret.push(item)
					}
				}
				else
				{
					ret.push(item)
				}
			});*/
		}
		,afterSave: function(err) {
			this.Super('afterSave', arguments);
			if(!err)
			{
				this.hide();
			}
		}
		,setDirect: function (data) {
			this.vm.$.data = data;
			this.$data = data;
			this.checkEmpty();
			return this;
		}
		,setData: function(data)
		{
			var self = this;
			self.$data = [];
			util.each(data, function (item, i) {
				if(item.IsTemplate)
				{
					self.onSelectMaterialGroup({
						param: item.Data
					});
				}
				else
				{
					self.$data.push({
						Sweety: [], Whisky: []
					});

					self.$indexSweety = self.$data.length -1;
					self.$indexWhisky = self.$data.length -1;
					self.onSelectSweety({
						param: item.Sweety
					});

					self.onSelectWhisky({
						param: item.Whisky
					});
				}
			});

			this.checkEmpty();
		}
		,hideMethod: function () {
			this.vm.set('hideMethod', true);
			return this;
		}
		,save: function () {
			var pop = this.$.namePop;
			if(pop)
			{
				pop.reset().show();
			}
		}
		,doSave: function (data, cb) {
			if(this.validate(data.Strategy))
			{
				this.checkWhiskyUrl(data.Strategy, function (forceUpdate) {
					data.WhiskyUrlForce = forceUpdate;
					cb(forceUpdate);
				});
			}
		}
		,onDialogOk: function (ev) {
			if(ev.name === 'namePop')
			{
				ev.from.hide();
				var data = {
					Strategy: this.getData(),
					Name: ev.param.Name
				};

				this.doSave(data, function () {
					pubjs.loading.show();
					pubjs.mc.send("materialGroup/add", data, function (err) {
						pubjs.loading.hide();
						if(err)
						{
							return pubjs.alert(err.message);
						}

						pubjs.alert(LANG('保存素材组成功'));
					});
				})
			}
		}
		,setSelectParam: function (param) {
			this.$.whiskyPop.setParam(param);
			this.$.sweetyPop.setParam(param);
			return this;
		}
		,reset: function()
		{
			this.$sweetyParam = {};
			this.$whiskyParam = {};
			this.$indexWhisky = -1;
			this.$indexSweety = -1;
			this.$sweetyIds = [];
			this.$whiskyIds = [];
			this.$data = [];
			this.vm.reset();
			var c = this.getConfig();
			if(c.hideMethod)
			{
				this.vm.set('hideMethod', true);
			}
			if(c.canImport)
			{
				this.vm.set('canImport', true);
			}
			if(c.canSave)
			{
				this.vm.set('canSave', true);
			}

			return this;
		},
		// 设置全局的创意包和落地页参数
		setSWParam: function (sweety, whisky) {
			this.$sweetyParam =  sweety;
			this.$whiskyParam = whisky;
			return this;
		},
	});

	exports.base = Base;

	var Popwin = popwin.extend({
		init:function(config) {
			config = pubjs.conf(config, {
				'title': LANG('创意包与落地页'),
				'silence': true,
				// 'width': 960,
				'size': 'l',
				//'style': {'bodyClass': 'pr uk-form'},
			});

			this.Super('init', arguments);
		},
		afterBuild:function() {
			this.Super('afterBuild', arguments);
			this.create('materialGroup', Base, {
				canImport: true,
				canSave: true
			});

			this.buildFromTemplate();
		},
		reset: function() {
			this.$.materialGroup.reset();
			return this;
		},
		doSave: function (data, cb) {
			return this.$.materialGroup.doSave(data, cb);
		},
		onOk: function() {
			var data = this.getData();
			var mod = this.$.materialGroup;
			var fire_name = this.getConfig('fire_name') || 'setCommonOk';
			if(mod.validateInfo(data))
			{
				this.fire(
					fire_name,
					{
						"data": data
					}
				);
				this.hide();
			}

			return false;
		},
		setData: function(data)
		{
			this.$.materialGroup.setDirect(data);
			return this;
		},
		setValue: function (data) {
			return this.$.materialGroup.setData(data);
		},
		getValue: function (data) {
			return this.$.materialGroup.getData(data);
		},
		getData: function()
		{
			var mod = this.$.materialGroup;
			return mod.getInfo();
		},
		// 设置全局的创意包和落地页参数
		setSWParam: function (sweety, whisky) {
			var mod = this.$.materialGroup;
			mod.setSWParam(sweety, whisky);
			return this;
		},
		checkWhiskyUrl: function (data, cb, getUrl) {
			return this.$.materialGroup.checkWhiskyUrl(data, cb, getUrl);
		}
	});

	exports.popwin = Popwin;
});